import json
import time
import random
import datetime
import requests
from requests.exceptions import ConnectionError
# import win32api, win32con
from xhsapi import XhsApi
from Request import Request
from xhs_tcp import CookieApp, XhsTcp
import config
from adsl import ADSL


class Sms(object):

    def __init__(self):
        self.username = config.xunyaosoft_username
        self.pwd = config.xunyaosoft_pwd
        self.request_obj = requests.session()

    def login(self):
        url = "http://api.xunyaosoft.com/zc/zhicode/api.php?code=signIn&uPhoneNo={username}&uPassword={pwd}".format(
            username=self.username,
            pwd=self.pwd
        )
        ret = self.request_obj.get(url=url)
        print(ret.text)
        time.sleep(6)

    def get_phonenum(self, name="小红书"):
        url = "http://api.xunyaosoft.com/zc/zhicode/api.php?code=getPhoneNo&projName={name}".format(
            name=name
        )
        ret = self.request_obj.get(url=url)
        print(ret.text)
        time.sleep(6)
        return ret.text

    def get_code(self, phonenumber, name="小红书"):
        url = "http://api.xunyaosoft.com/zc/zhicode/api.php?code=getMsg&projName={name}&phoneNo={phonenumber}".format(
            name=name,
            phonenumber=phonenumber
        )
        ret = self.request_obj.get(url=url)
        print(ret.text)
        time.sleep(6)
        return ret.text

class XhsShixin(object):
    def __init__(self, remote_computer_name, cid):
        if not remote_computer_name:
            exit("没传远程设备名称")
        self.machine_num = 100
        self.request = Request(remote_computer_name)
        self.current_ip = self.request.get_current_ip()
        self.xhsapi = XhsApi(cid)
        # self.adsl_obj = ADSL()
        # self.switch_ip()

        # self.init_devices()
        print("============设备初始化完毕===========")
        # exit()

        # machine_list = self.request.get_machine_list()
        # random.shuffle(machine_list)
        # for machine_name in machine_list:
        #     print('machine_name -->', machine_name)
        #     # machine_name = "1598574594818"
        #     if self.request.check_login_xhs(machine_name):  # 已登录
        #         self.init_xhsapi()
        #         flag_send = self.send_msg(machine_name)
        #         flag_get = self.get_new_msg(machine_name)
        #
        #         if flag_send or flag_get:
        #             self.switch_ip()

        # machine_name = "1599294682078"
        # if self.request.check_login_xhs(machine_name):  # 已登录
        #     self.init_xhsapi()
        #     flag_send = self.send_msg(machine_name)
        #     flag_get = self.get_new_msg(machine_name)
        #
        #     if flag_send or flag_get:
        #         self.switch_ip()


    def init_xhsapi(self):
        self.xhsapi = XhsApi('8a23d07c03ba1e59')

    def switch_ip(self):
        self.adsl_obj.reconnect()
        print("当前ip: ", self.request.get_current_ip())
        # win32api.keybd_event(121, 0, 0, 0)
        # win32api.keybd_event(121, 0, win32con.KEYEVENTF_KEYUP, 0)
        # time.sleep(5)
        #
        # n = 1
        # while True:
        #     try:
        #         current_ip = self.request.get_current_ip()
        #         if current_ip != self.current_ip:
        #             print("当前ip: ", current_ip)
        #             break
        #         else:
        #             n += 1
        #             if n > 50:
        #                 win32api.keybd_event(121, 0, 0, 0)
        #                 win32api.keybd_event(121, 0, win32con.KEYEVENTF_KEYUP, 0)
        #                 time.sleep(5)
        #         time.sleep(2)
        #     except requests.exceptions.ConnectionError as e:
        #         print('e -->', e)

    # 休息随机秒
    def sleep_random(self, t1=0, t2=0):
        if t1 > 0 and t2 > 0:
            sleep_time = random.random() + random.randint(t1, t2)
        elif t1 > 0:
            sleep_time = t1
        else:
            sleep_time = random.random() + random.randint(1, 2)
        print(str(datetime.datetime.now()) + "   休息随机秒 %s" % sleep_time)
        time.sleep(sleep_time)


    # 登录小红书
    def login(self, machine_name):
        print("get_current_ip -->", self.request.get_current_ip())
        print('machine_name -->', machine_name)

        self.switch_ip()
        self.xhs_login_phone(machine_name)

        # username, password = self.request.get_wb_user(machine_name)
        # self.switch_ip()
        # result_data = self.xhs_login(username, password)
        # if result_data:
        #     result_data['machine_num'] = machine_name
        #     self.request.update_user_info(result_data)



    # 初始化设备
    def init_devices(self):
        while True:
            machine_list = self.request.get_machine_list()
            print("当前设备数:", len(machine_list))
            if len(machine_list) < self.machine_num:
                self.create_devices()
            else:
                break

        # 检测账号是否登录
        machine_list = self.request.get_machine_list()
        random.shuffle(machine_list)
        for machine_name in machine_list:
            if not self.request.check_login_xhs(machine_name):  # 未登录
                try:
                    self.login(machine_name)
                except TypeError as e:
                    print('e -->', e)
                    if 'NoneType' in str(e):
                        continue
                    exit()
                except ConnectionError as e:
                    continue


                # time.sleep(10)
                # exit()


    # 创建新设备
    def create_devices(self):
        print("创建新设备")
        name = str(int(time.time() * 1000))
        self.request.init(name)
        # self.request.get_wb_user(name)
        self.request.check_login_xhs(name)

    def xhs_login_phone(self, machine_name, phonenum=""):
        result_data = {
            'blogger_id': '',
            'blogger_name': '',
            'blogger_img': '',
            'device_data': '',
        }
        self.init_xhsapi()
        self.xhsapi.init_new_device_params()
        register_smid_ret = self.xhsapi.register_smid()
        print('register_smid_ret:' + register_smid_ret)

        smid = json.loads(register_smid_ret)['detail']['deviceId']
        print('smid:' + smid)
        self.xhsapi.set_smid(smid)

        # 激活用户
        active_user_ret = self.xhsapi.active_user()
        print('active_user_ret:' + active_user_ret)
        success = json.loads(active_user_ret)['success']
        if not success:
            crypt_method = json.loads(active_user_ret)['crypt_method']
            print('crypt_method: ' + crypt_method)
            self.xhsapi.set_crypt_method(crypt_method)

        active_user_ret = self.xhsapi.active_user()
        print('active_user_ret:' + active_user_ret)

        # if 'data' not in json.loads(active_user_ret):
        #     return False

        # 设置session id
        session_id = ''
        active_json = json.loads(active_user_ret)
        if 'data' in active_json:
            session_id = active_json['data']['session']
            print('session_id:' + session_id)

            # 短信验证码登录
            if len(session_id) == 0:
                # print("需要短信验证,退出")
                # exit()
                # 发送短信验证码
                # phone = '13903810993'
                # phone = input("请输入手机号:")
                sms_obj = Sms()
                sms_obj.login()
                if not phonenum:
                    while True:
                        phonenum = sms_obj.get_phonenum()
                        if not phonenum.startswith("171"):
                            break


                send_code_ret = self.xhsapi.send_sms_code(phonenum)
                print('send_code_ret:' + send_code_ret)

                n = 0
                while True:
                    n += 1
                    # time.sleep(5)
                    sms_code = sms_obj.get_code(phonenum)
                    if "您的验证码是" in sms_code:
                        sms_code = sms_code.split(":")[1].split('，')[0].strip()
                        break
                    print('sms_code:' + sms_code)

                    if n > 10:
                        print("未获取到验证码,退出")
                        return

                # sms_code = input('请输入短信验证码：')
                print('sms_code:' + sms_code)

                # 验证短信验证码
                check_code_ret = self.xhsapi.check_sms_code(phonenum, sms_code)
                print('check_code_ret:' + check_code_ret)

                # 用短信验证码登录
                mobile_token = json.loads(check_code_ret)['data']['token']
                print('mobile_token:' + mobile_token)
                while True:
                    try:
                        result_data = self.xhsapi.login_with_sms(phonenum, mobile_token)
                        session_id = result_data['session']
                        blogger_id = result_data['userid']
                        blogger_name = result_data['nickname']
                        blogger_img = result_data['images']
                        register_time = result_data['register_time']
                        print('session_id:' + session_id)

                        if len(session_id) == 0:
                            print('session is empty, exit!')
                            exit()

                        # 设置session_id
                        self.xhsapi.set_session_id(session_id)

                        # 获取首页推荐
                        home_feed = self.xhsapi.get_home_feed()
                        print('home_feed:' + home_feed)
                        to_userid = json.loads(home_feed)['data'][0]['user']['userid']
                        print('to_userid -->', to_userid)

                        # 获取用户信息
                        # user_info = xhsapi.get_user_info('5c3fe348000000000603daaf')
                        # print('user_info:' + user_info)

                        print(self.xhsapi.get_register_user_data())
                        device_data = self.xhsapi.get_register_user_data()
                        device_data['phone'] = phonenum
                        device_data['register_time'] = register_time
                        # send_msg(device_data, blogger_id, blogger_name, blogger_img, to_userid)

                        ck_data = {'blogger_data': [], 'device_data': device_data, 'blogger_id': blogger_id}
                        userid = ck_data['blogger_id']
                        sid = ck_data['device_data']['sid']
                        device_id = ck_data['device_data']['device_id']
                        smid = ck_data['device_data']['smid']

                        # to_userid = "5c3fe348000000000603daaf"
                        msg = "你好,可以加个关注不"

                        cookie_app_obj = CookieApp(userid, sid, device_id, smid, to_userid, msg)
                        obj = XhsTcp(cookie_app_obj)
                        print('obj.ok8 -->', obj.ok8)
                        if obj.ok8:
                            # request_obj = Request("sms_register")
                            # name = str(int(time.time() * 1000))
                            # request_obj.init(name)
                            result_data = {
                                'blogger_id': blogger_id,
                                'blogger_name': blogger_name,
                                'blogger_img': blogger_img,
                                'device_data': json.dumps(device_data),

                                'machine_num': machine_name
                            }
                            self.request.update_user_info(result_data)
                            self.request.check_login_xhs(machine_name)

                        # 获取接口使用情况
                        api_access_info = self.xhsapi.get_api_access_info()
                        print('api_access_info:' + api_access_info)

                        break

                    except ConnectionError:
                        pass

    def xhs_login(self, username, password):
        result_data = {
            'blogger_id': '',
            'blogger_name': '',
            'blogger_img': '',
            'device_data': '',
        }
        self.init_xhsapi()
        self.xhsapi.init_new_device_params()
        register_smid_ret = self.xhsapi.register_smid()
        print('register_smid_ret:' + register_smid_ret)

        smid = json.loads(register_smid_ret)['detail']['deviceId']
        print('smid:' + smid)
        self.xhsapi.set_smid(smid)

        # 激活用户
        active_user_ret = self.xhsapi.active_user()
        print('active_user_ret:' + active_user_ret)
        success = json.loads(active_user_ret)['success']
        if not success:
            crypt_method = json.loads(active_user_ret)['crypt_method']
            print('crypt_method: ' + crypt_method)
            self.xhsapi.set_crypt_method(crypt_method)

        active_user_ret = self.xhsapi.active_user()
        print('active_user_ret:' + active_user_ret)

        # if 'data' not in json.loads(active_user_ret):
        #     return False

        # 设置session id
        session_id = ''
        active_json = json.loads(active_user_ret)
        if 'data' in active_json:
            session_id = active_json['data']['session']
            print('session_id:' + session_id)

        # 微博登录
        if len(session_id) == 0:
            result = self.xhsapi.login_with_weibo_app(username, password)
            if result:
                print('user_info result -->', result)
                session_id = result['session']

        # 微博h5登录
        if len(session_id) == 0:
            result = self.xhsapi.login_with_weibo_h5(username, password)
            if result:
                print('user_info result -->', result)
                session_id = result['session']

        if len(session_id) == 0:
            print('session is empty, exit!')
            return False


        userid = result['userid']
        print('session_id:' + session_id)
        print('userid:' + userid)

        result_data['blogger_id'] = userid
        result_data['blogger_name'] = result['nickname']
        result_data['blogger_img'] = result['images']

        # 设置session_id
        self.xhsapi.set_session_id(session_id)

        # 获取首页推荐
        home_feed = self.xhsapi.get_home_feed()

        result_data['device_data'] = json.dumps(self.xhsapi.get_register_user_data())
        # print(self.xhsapi.get_register_user_data())
        return result_data

    # 发送消息
    def send_msg(self, machine_name):

        task_data = self.request.get_message_task(machine_name)
        if task_data:
            print('task_data -->', task_data)
            ck_data = self.request.get_blogger_list(machine_name)
            print('ck_data -->', ck_data)
            # userid = "5f4b02f90000000001006277"
            # sid = "session.1598752227482778345076"
            # device_id = "d1c7d312-f226-4fc1-acb2-9ad11826b5cd"
            # smid = "20200830095024dde1263afe41c820e24ee045f06e569c0186de0cc4b6e6ae"
            # to_userid = "5ef0c195000000000101df16"
            # msg = "你想了解的这款现在有折扣，你可以+v  15641 0072 43 我发给你看看，部分包包有五折，我们支持 货到付款。"
            userid = ck_data['blogger_id']
            sid = ck_data['device_data']['sid']
            device_id = ck_data['device_data']['device_id']
            smid = ck_data['device_data']['smid']
            to_userid = task_data['blogger_url'].split('/')[-1]
            msg = task_data['message']
            task_id = task_data['task_id']
            cookie_app_obj = CookieApp(userid, sid, device_id, smid, to_userid, msg)
            obj = XhsTcp(cookie_app_obj)
            if obj.user_auth:
                self.request.post_message_task(task_id)
            else:
                result_data = {
                    'blogger_name': '',
                    'machine_num': machine_name
                }
                self.request.update_user_info(result_data)
            return True

    # 获取新消息
    def get_new_msg(self, machine_name):

        ck_data = self.request.get_blogger_list(machine_name)
        print('ck_data -->', ck_data)

        if ck_data:
            # print('ret -->', ret)
            # [{"blogger_id": "5c7a0ab60000000010029c2e"}]

            blogger_data = ck_data['blogger_data']
            device_data = ck_data['device_data']
            if len(blogger_data) > 0:
                print("===================== 获取私信消息列表 =====================")
                for blogger in blogger_data:
                    self.sleep_random()
                    blogger_id = blogger['blogger_id']
                    self.xhsapi.set_register_user_data(device_data)

                    if device_data['crypt_method'] == '':
                        ret = self.xhsapi.get_home_feed()
                        # print('get_home_feed -->', ret)
                        result_dict = json.loads(ret)
                        if 'crypt_method' in result_dict:
                            crypt_method = result_dict['crypt_method']
                            self.xhsapi.set_crypt_method(crypt_method)

                            # 更新数据
                            user_info = {
                                'machine_num': machine_name,
                                'device_data': json.dumps(self.xhsapi.get_register_user_data())
                            }
                            self.request.update_user_info(user_info)
                        # obj.sleep_random()

                    print("blogger_id -->", blogger_id)
                    ret = self.xhsapi.get_message(blogger_id)
                    print('ret -->', ret)
                    result_dict = json.loads(ret)

                    if result_dict['success']:
                        # print("result_dict['data'] -->", result_dict['data'])
                        data = {
                            'msg_data': json.dumps(result_dict['data']),
                            'blogger_id': blogger_id,
                            'machine_num': machine_name,
                        }
                        ret = self.request.rsync_msg(data)
                    else:
                        if result_dict['error_message'] == "用户校验失败":
                            if "phone" in device_data:
                                self.xhs_login_phone(machine_name, device_data['phone'])


                return True
if __name__ == '__main__':
    remote_computer_name = config.RemoteComputerName
    cid = config.CID
    # obj = XhsShixin(remote_computer_name)

    obj = XhsShixin(remote_computer_name, cid)
    # device_data = {"device_id": "24b72b11-ea39-4172-9cac-6c5ec7e6b45f", "smid": "2020083108111918f1746c56fc657889b23b505457bb8001577640976f051e", "sid": "session.1598832714642135150397", "fid": "1598832667104b5382889a82ed20d27623b2d40c965a", "crypt_method": "5f97953f0fa1cb58"}
    device_data = {'device_id': '4a775600-8ec1-4a24-b91f-28ec590c6f70', 'smid': '20201218155357bef3efd447708c254749312f33117b7a0150160f36bdc5d3', 'sid': 'session.1608278098474126468385', 'fid': '160827803410a9631e4410a467feb29b5fb56e08b51d', 'crypt_method': '7874f36821a2e1a4'}
    obj.xhsapi.set_register_user_data(device_data)
    result = obj.xhsapi.get_message("5cb54ef500000000170043f6")
    print('result -->', result)

    # obj = XhsShixin(remote_computer_name, cid)

    # while True:
    #     try:
    #         obj = XhsShixin(remote_computer_name, cid)
    #     except:
    #         pass